<template>
  <div class="brithPop">
    <van-datetime-picker
      v-model="currentDate"
      type="date"
      :min-date="minDate"
      :max-date="maxDate"
      @cancel="$emit('close')"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
// 导入时间格式化工具
import * as dayjs from 'dayjs'
// 编辑用户个人资料api
import { edituser } from '@/assets/api/user'

export default {
  name: 'brithPop',
  props: {
    defaultdate: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      minDate: new Date(1949, 10, 1),
      maxDate: new Date(),
      currentDate: new Date(this.defaultdate ? this.defaultdate : new Date())
    }
  },
  methods: {
    async onConfirm(val) {
      const time = dayjs(val).format('YYYY-MM-DD')
      this.$toast.loading({
        message: '保存中',
        forbidClick: true,
        // 持续展示
        duration: 0
      })
      if (time === this.defaultdate) {
        this.$toast('更新成功')
        return this.$emit('close')
      }
      try {
        // 发起请求
        var { data: res } = await edituser({
          birthday: time
        })
      } catch {
        // 处理请求错误
        return this.$toast('更改失败，请取消在试')
      }
      // 告知父组件更改完毕
      this.$toast('更新成功')
      this.$emit('editOk', time)
    }
  }
}
</script>

<style lang="less" scoped></style>
